#include <stdio.h>
#include <stdlib.h>

#include "tree.h"
    


void tree_insert(TREE **node,DataType *data){
	
    if((*node) == NULL){
		
        TREE *new = NULL;
        new = malloc(sizeof(TREE));
        if(new == NULL){
            fprintf(stdout, "创建新节点失败");
            exit(1);
        }
        new->Tleft = NULL;
        new->Tright = NULL;
        new->data = *data;
        *node = new;

    }
    
    else if(*data <= (*node)->data){
        tree_insert(&(*node)->Tleft, data);
    }
    else {
        tree_insert(&(*node)->Tright, data);
    }

}


TREE *tree_init(DataType *data,int size){
    TREE *head_node = NULL;
    DataType *value = data;
	int n = size;
    while((n--)){
        tree_insert(&head_node,value);
        value++;
    }
    return head_node;
}

// 获取树的深度
int tree_depth(TREE *tree) {
	if (tree == NULL) 
		return 0;
	
	int depthLeft, depthRight;
	depthLeft = tree_depth(tree->Tleft);
	depthRight = tree_depth(tree->Tright);

	return 1 + (depthLeft > depthRight ? depthLeft : depthRight);
}

//为了结构美观，数据选取不大于两位数。
//树结构打印主程序
void tree_display (TREE *tree,int level) {
	int i;
	if (tree != NULL) {
		for (i = 0; i < level; i += 1) {
			printf("  ");
		}
		printf("%d",tree->data);
		printf("\n");
		tree_display(tree->Tleft,(level-1));
		tree_display(tree->Tright,(level+1));

		
	}

	

}

